package com.btpj.module_main.ui.project

import android.os.Bundle
import androidx.paging.PageKeyedDataSource
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.btpj.jetpack.base.BaseListFragment
import com.btpj.jetpack.datasource.MutablePageKeyedDataSource
import com.btpj.module_main.adapter.NavPageAdapter
import com.btpj.module_main.data.entity.ProjectItemSub
import com.scwang.smartrefresh.layout.api.RefreshLayout

class TabItemFragment : BaseListFragment<ProjectItemSub, TabItemViewModel>() {

    companion object {
        fun newInstance(id: Int): TabItemFragment {
            return TabItemFragment().apply {
                arguments = Bundle().apply {
                    putInt("id", id)
                }
            }
        }
    }

    override fun onCreateViewAfter() {
        super.onCreateViewAfter()
        hiddenActionBar()
        mViewModel.mId = requireArguments().getInt("id")
    }

    override fun generateAdapter(): PagedListAdapter<ProjectItemSub, RecyclerView.ViewHolder> {
        return NavPageAdapter(requireContext()) as PagedListAdapter<ProjectItemSub, RecyclerView.ViewHolder>
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mViewModel.mDataSource!!.invalidate()
        finishRefresh()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        val currentList = mAdapter.currentList
        if (currentList == null || currentList.size <= 0) {
            return
        }

        val config = currentList.config
        val count = currentList.size / 15

        mViewModel.getTabPageData(count,
            object : PageKeyedDataSource.LoadCallback<Int, ProjectItemSub>() {
                override fun onResult(data: MutableList<ProjectItemSub>, adjacentPageKey: Int?) {
                    val dataSource = MutablePageKeyedDataSource<ProjectItemSub>()
                    dataSource.data.addAll(currentList)
                    dataSource.data.addAll(data)
                    val pageList = dataSource.buildNewPageList(config)
                    mAdapter.submitList(pageList)
                }
            })
        finishRefresh()
    }
}